package org.micode.libs.dao.helper;

import org.micode.common.utils.BeanExtUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BeanHelper {

    public static <D> void fillUpdFields(D dest, Long updUserId, String loginApp, String loginIp) {
        if (null == dest) {
            return ;
        }

        if (null != updUserId) {
            findAndSetField(dest, "ModifiedUserId", updUserId);
            findAndSetField(dest, "updUser", updUserId);
        }

        findAndSetField(dest, "LoginApp", loginApp);
        findAndSetField(dest, "updProg", loginApp);

        findAndSetField(dest, "LoginIp", loginIp);
        findAndSetField(dest, "updIp", loginIp);
    }

    private static <D> void findAndSetField(D dest, String fieldName, Object fieldValue) {
        if (BeanExtUtils.findFieldByName(dest, fieldName)) {
            BeanExtUtils.setFieldByName(dest, fieldName, fieldValue);
        } else {
            log.trace("Not found: {}.{}", dest.getClass().getSimpleName(), fieldName);
        }
    }

    public static <T, D> void copyUpdFields(T source, D dest) {
        if (null == source || null == dest) {
            return ;
        }

        Object value = BeanExtUtils.getFieldValueByName(source, "ModifiedUserId");
        Long userId = null;
        if (null != value) {
            try {
                userId = Long.valueOf(value.toString());
            } catch(Exception e) {
                log.warn("Failed to convert UserId to long type, source value is: {}", value.toString());
            }
        }

        if (null == userId) {
            value = BeanExtUtils.getFieldValueByName(source, "userId");
            if (null != value) {
                try {
                    userId = Long.valueOf(value.toString());
                } catch(Exception e) {
                    log.warn("Failed to convert UserId to long type, source value is: {}", value.toString());
                }
            }
        }

        fillUpdFields(dest, userId, getStrValue(source, "LoginApp"), getStrValue(source, "LoginIp"));
    }

    private static <T> String getStrValue(T source, String fieldName) {
        Object value = BeanExtUtils.getFieldValueByName(source, fieldName);
        if (null != value) {
            return value.toString();
        }
        return null;
    }

}
